from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from flask_restful import inputs
from flask import current_app

from . import constants
from models.news import Article
from cache import article as cache_article


class SearchResource(Resource):

    def get(self):
        # 检验参数
        qs_parser = RequestParser()
        qs_parser.add_argument('q', type=inputs.regex(r'^.{1,50}$'), required=True, location='args')

        qs_parser.add_argument('page', type=inputs.positive, required=False, location='args')

        qs_parser.add_argument('per_page', type=inputs.int_range(constants.DEFAULT_SEARCH_PER_PAGE_MIN,
                                                                 constants.DEFAULT_SEARCH_PER_PAGE_MAX, 'per_page'),
                               required=False, location='args')

        req = qs_parser.parse_args()
        q = req.q
        page = 1 if not req.page else req.page
        per_page = constants.DEFAULT_SEARCH_PER_PAGE_MIN if not req.per_page else req.per_page

        # 查询es
        # per_page = 10
        # 1P  0-9
        # 2P 10-19
        query_dict = {
            "from": per_page * (page - 1),
            "size": per_page,
            "_source": ["article_id", "title"],
            "query": {
                "bool": {
                    "must": {
                        "match": {
                            "_all": q
                        }
                    },
                    "filter": {
                        "term": {
                            "status": Article.STATUS.APPROVED
                        }
                    }
                }
            }
        }

        # es.search(index=库名, doc_type=表名 类型, body=查询条件 字典)
        ret = current_app.es.search(index='articles', doc_type='article', body=query_dict)

        # {
        #   "took" : 43,
        #   "timed_out" : false,
        #   "_shards" : {
        #     "total" : 3,
        #     "successful" : 3,
        #     "skipped" : 0,
        #     "failed" : 0
        #   },
        #   "hits" : {
        #     "total" : 39,
        #     "max_score" : 10.8020935,
        #     "hits" : [
        #       {
        #         "_index" : "articles_v2",
        #         "_type" : "article",
        #         "_id" : "1286",
        #         "_score" : 10.8020935,
        #         "_source" : {
        #           "article_id" : 2,
        #           "title" : "python如何使用web3py与以太坊投资智能合约交互\n原\n荐"
        #         }
        #       },

        total_count = ret['hits']['total']

        results = []

        for item in ret['hits']['hits']:
            # item -> {
            #         "_index" : "articles_v2",
            #         "_type" : "article",
            #         "_id" : "1286",
            #         "_score" : 10.8020935,
            #         "_source" : {
            #           "article_id" : 1286,
            #           "title" : "python如何使用web3py与以太坊投资智能合约交互\n原\n荐"
            #         }
            #       }
            # article_id = item['_source']["article_id"]
            article_id = item['_id']

            article_dict = cache_article.ArticleInfoCache(article_id).get()

            if article_dict:
                results.append(article_dict)



        # 返回
        # {
        # 	"message": "OK",
        # 	"data": {
        # 		"page": xx,
        # 		"per_page": xx,
        # 		"total_count": xx,
        # 		"results": [
        # 			{
        # 				"article_id":xx,
        # 				"title": xx,
        # 				"cover": xx
        # 			},
        # 			...
        # 		]
        # 	}
        # }

        return {"page": page, "per_page": per_page, "total_count": total_count, "results": results}


class SuggestionResource(Resource):
    """
    联想建议
    """
    def get(self):
        """
        获取联想建议
        """
        qs_parser = RequestParser()
        qs_parser.add_argument('q', type=inputs.regex(r'^.{1,50}$'), required=True, location='args')
        args = qs_parser.parse_args()
        q = args.q

        # 先尝试自动补全建议查询
        query = {
            'from': 0,
            'size': 10,
            '_source': False,
            'suggest': {
                'word-completion': {
                    'prefix': q,
                    'completion': {
                        'field': 'suggest'
                    }
                }
            }
        }
        ret = current_app.es.search(index='completions', body=query)
        options = ret['suggest']['word-completion'][0]['options']

        # 如果没得到查询结果，进行纠错建议查询
        if not options:
            query = {
                'from': 0,
                'size': 10,
                '_source': False,
                'suggest': {
                    'text': q,
                    'word-phrase': {
                        'phrase': {
                            'field': '_all',
                            'size': 1
                        }
                    }
                }
            }
            ret = current_app.es.search(index='articles', doc_type='article', body=query)
            options = ret['suggest']['word-phrase'][0]['options']

        results = []
        for option in options:
            if option['text'] not in results:
                results.append(option['text'])

        return {'options': results}







